<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <script>
    // race
    function promiseRace(promiseArray) {
      return new Promise((resolve, reject) => {
        if (!Array.isArray(promiseArray)) {
          //传入的参数是否为数组
          return reject(new Error("传入的参数不是数组！"));
        }
        for (let i = 0; i < promiseArray.length; i++) {
          Promise.resolve(promiseArray[i])
            .then((res) => resolve(res))
            .catch((res) => reject(res));
        }
      });
    }

    // all
    function promiseAll(promiseArray) {
      //请在此处补全代码
      return new Promise((resolve, reject) => {
        if (!Array.isArray(promiseArray)) {
          //传入的参数是否为数组
          return reject(new Error("传入的参数不是数组！"));
        }

        const res = [];
        let counter = 0; //设置一个计数器
        for (let i = 0; i < promiseArray.length; i++) {
          // 防止item不是promise
          Promise.resolve(promiseArray[i])
            .then((value) => {
              counter++; //使用计数器返回 必须使用counter
              res[i] = value;
              if (counter === promiseArray.length) {
                resolve(res);
              }
            })
            .catch((e) => reject(e));
        }
      });
    }

    const p1 = new Promise((res, rej) => {
      setTimeout(() => {
        res("p1");
      }, 1000);
    });

    const p2 = new Promise((res, rej) => {
      setTimeout(() => {
        res("p2");
      }, 2000);
    });

    const p3 = new Promise((res, rej) => {
      setTimeout(() => {
        res("p3");
      }, 3000);
    });

    const test = promiseAll([p1, p2, p3])
      .then((res) => console.log(res))
      .catch((e) => console.log(e));

    const test1 = promiseRace([p1, p2, p3])
      .then((res) => console.log(res))
      .catch((e) => console.log(e));

    console.log(test);
    console.log(test1);
  </script>
</body>

</html>